package org.fb.boot;

import org.fb.service.UserServiceImpl;
import org.fb.utils.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author fanbo@imoran.net
 * @date 2021/2/6 18:33
 */
@Component
public class ServerBoot {

    @Value("${spring.application.name:server}")
    public String appName;

    @Value("${rpc.port:8080}")
    public Integer port;

    @Value("${zookeeper.server}")
    private String zookeeperServer;

    @Value(("${zookeeper.sessionTimeoutMs}"))
    private int sessionTimeoutMs;

    @Value("${zookeeper.connectionTimeoutMs}")
    private int connectionTimeoutMs;

    @Value("${zookeeper.maxRetries}")
    private int maxRetries;

    @Value("${zookeeper.baseSleepTimeMs}")
    private int baseSleepTimeMs;


    /**
     * 启动RPC服务， 并注册服务ip:port到Zookeeper上
     */
    @PostConstruct
    public void registerServer2Zookeeper() throws UnknownHostException {
        try {
            System.out.println("RPC server " + appName + "started @ " + "127.0.0.1:" + port);
            UserServiceImpl.startServer("127.0.0.1", port);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ZkClient zkClient = new ZkClient();
        zkClient.init();
        //String hostAddress = InetAddress.getLocalHost().getHostAddress();
        String hostAddress = "127.0.0.1";
        zkClient.register(appName, hostAddress, port);
    }


}
